#include <cstdint>
#include<iostream>
#include<memory>
#include "Common.hpp"
#include "InetAddr.hpp"
#include "Log.hpp"
#include"Socket.hpp"
#include<sys/wait.h>
#include<functional>

using namespace SocketModule;
using namespace LogModule;

using ioservice_t = std::function<void(std::shared_ptr<Socket>& sock, InetAddr& cilent)>;
class TcpServer
{
public:
    TcpServer(uint16_t port, ioservice_t service)
    :   _port(port),
        _listensockptr(std::make_unique<TcpSocket>()),
        _service(service),
        _isrunning(false)
    {
        _listensockptr->BuildTcpSocketMethod(_port);//  初始化   
    }
    
    void Start()
    {
        _isrunning = true;
        while(_isrunning)
        {
            InetAddr client;
            //和cilent通信  client网络地址
            auto sock = _listensockptr->Accept(&client);
            if(sock == nullptr)
            {
                continue;
            }
            LOG(LogLevel::DEBUG)<<"accept success: "<< client.StringAddr();
            
            pid_t id = fork();
            if(id < 0)
            {   
                LOG(LogLevel::FATAL)<<"fork error ....";
                exit(FORK_ERR);
            }
            else if(id == 0)
            {
                //子进程
                _listensockptr->Close();//子进程关闭不需要的文件描述符
                if(fork() > 0)
                exit(OK);
                _service(sock, client);
                sock->Close();
                exit(OK);
            }
            else 
            {
                sock->Close();
            }
        }
        _isrunning = false;
    }
    ~TcpServer()
    {}
private:
    uint16_t _port;
    std::unique_ptr<Socket> _listensockptr;
    bool _isrunning;
    ioservice_t _service; 
};